package cn.jee.controller;

import cn.jee.entity.User;
import cn.jee.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Map;

@Controller
public class LoginController {
  @RequestMapping("/login_input")
  public String loginInput(){
    return "login";
  }
  @RequestMapping("/login")
  public String login(String username, String password, Model model, HttpSession session){
    System.out.println(username);
    model.addAttribute("username",username);
    session.setAttribute("login_user",username);
    return "login_suc";
  }
  @Autowired
  UserService service;
  @RequestMapping("/loginDb")
  public String loginDb(User user, Model model, HttpSession session, RedirectAttributes redirectAttributes){
    boolean isSuc=service.login(user);
    if(isSuc){
      model.addAttribute("username",user.getUsername());
      session.setAttribute("login_user",user.getUsername());
      return "login_suc";//forward
    }else{//重定向
      model.addAttribute("username","重定向看不到原来的值");
      redirectAttributes.addAttribute("redirect_msg","重定向传值");
      //只显示一次，第二次不见
      redirectAttributes.addFlashAttribute("flash_msg","只显示一次，刷新不见");
      return "redirect:login_fail";//重定向只能指向action
    }
  }
  @RequestMapping("login_fail")
  public String loginFail(){
    return "login_fail";
  }
  @ResponseBody
  @RequestMapping("/login_async")
  public Map loginAsync(@RequestBody User user){
    boolean isSuc=service.login(user);
    if(isSuc){
      return Map.of("code",0,"msg","");
    }else{
      return Map.of("code",1,"msg","用户名或密码错误");
    }
  }
}
